﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using log4net;
using Model;
using Newtonsoft.Json.Linq;
using Service;


[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Print
{
    public partial class Login : Form
    {
        int state=0;//航信反复提交
        int start;//缓存
                  //Listening
                  //WebSend
                  //最大化3 最小化2 正常化1
                  //SetWindowPos -1置顶 -2取消置顶
        //BlockInput TRUE 锁定 False 激活

        private IntPtr? HeWindows;
        private IntPtr? Windows;
        private IntPtr? Common;
        private static readonly object lockHelper = new object();
        private static readonly ILog log = LogManager.GetLogger(typeof(Nullable));

        const int MOUSEEVENTF_MOVE = 0x0001;     // 移动鼠标           (十):1
        const int MOUSEEVENTF_LEFTDOWN = 0x0002; //模仿鼠标左键按下    (十):2
        const int MOUSEEVENTF_LEFTUP = 0x0004; //模仿鼠标左键抬起    (十):4
        const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模仿鼠标右键按下    (十):8
        const int MOUSEEVENTF_RIGHTUP = 0x0010; //模仿鼠标右键抬起    (十):16
        const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;// 模仿鼠标中键按下    (十):32
        const int MOUSEEVENTF_MIDDLEUP = 0x0040;// 模仿鼠标中键抬起    (十):64
        const int MOUSEEVENTF_ABSOLUTE = 0x8000; //标示是否采取绝对坐标    (十):32768
        private const int WM_SETTEXT = 0x000C;
        const int BM_CLICK = 0xF5;//鼠标点击事件
        const int WM_GETTEXT = 0xd;//获取文本
        const int WM_CLOSE = 0x0010;

        /// 获取指定窗口的设备场景
        ///
        /// 将获取其设备场景的窗口的句柄。若为0，则要获取整个屏幕的DC
        /// 指定窗口的设备场景句柄，出错则为0
        [DllImport("user32.dll")]
        public static extern IntPtr GetDC(IntPtr hwnd);

        ///
        /// 释放由调用GetDC函数获取的指定设备场景
        ///
        /// 要释放的设备场景相关的窗口句柄
        /// 要释放的设备场景句柄
        /// 执行成功为1，否则为0
        [DllImport("user32.dll")]
        public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool EnumThreadWindows(uint dwThreadid, EnumThreadDelegate lpfn, IntPtr lParam);//列举特定窗体的子窗体

        [DllImport("gdi32.dll")]
        public static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
        public Color GetColor(int x, int y)
        {
            uint pixel;
            Color color;
            IntPtr hdc = IntPtr.Zero;
            pixel = GetPixel(hdc, x, y);
            ReleaseDC(IntPtr.Zero, hdc);
            color = Color.FromArgb((int)(pixel & 0x000000FF), (int)(pixel & 0x0000FF00) >> 8, (int)(pixel & 0x00FF0000) >> 16);
            return color;
        }
        [DllImport("user32.dll", EntryPoint = "GetWindowText")]
        public static extern int GetWindowText(
          IntPtr hWnd,
          StringBuilder lpString,
          int nMaxCount
      );
        [DllImport("user32.dll")]
        private static extern int GetWindowTextLength(IntPtr hwnd);

        delegate bool EnumThreadDelegate(IntPtr hwnd, IntPtr lParam);

        IntPtr targetFormHwnd = IntPtr.Zero;
        private bool EnumThreadCallback(IntPtr hwnd, IntPtr lParam)
        {
            bool result = true;

            int length = GetWindowTextLength(hwnd);
            StringBuilder lpString = new StringBuilder(length + 1);
            GetWindowText(hwnd, lpString, lpString.Capacity);

            if (lpString.ToString().Contains("增值税发票税控开票软件"))
            {
                StaffData.VersionData = lpString.ToString();
                log.InfoFormat("航信版本：" + StaffData.VersionData);
                targetFormHwnd = hwnd;
                return false;
            }

            return result;
        }
        uint CWP_ALL = 0x0000;
        [DllImport("user32.dll")]
        static extern IntPtr ChildWindowFromPoint(IntPtr hWndParent, Point Point);


        [DllImport("user32.dll")]
        private static extern int GetWindowRect(IntPtr hwnd, ref Service.WindowsAPIService.Rect lpRect);

        [DllImport("user32.dll")]
        static extern IntPtr ChildWindowFromPointEx(IntPtr hWndParent, Point pt, uint uFlags);

        public const int WH_MOUSE_LL = 14;
        public Service.WindowsAPIService.HookProc hProc;

        [DllImport("AspriseOCR.dll", EntryPoint = "OCRpart", CallingConvention = CallingConvention.Cdecl)]
        static extern IntPtr OCRpart(string file, int type, int startX, int startY, int width, int height);


        IWindowAPI WindowsAPI = null;
        IWebRequest WebRequest = null;
        IFile FileIO = null;
        IOCR OCR = null;
     
        public Login()
        {
            InitializeComponent();
           

        }
        #region
        //private void Login_Load(object sender, EventArgs e)
        //{
        //    StaffData.ListOffLine = new List<EntityStaff>();
        //    WindowsAPI = new WindowsAPIService();
        //    FileIO = new FileService();
        //    WebRequest = new WebRequestService();
        //    StaffData.VersionData = FileIO.SeanTitle();
        //OCR = new OCRService();
        //    //EntityStaff DATA = new EntityStaff()
        //    //{
        //    //    InvNo = BondData.InvNo,
        //    //    Money = BondData.Money,
        //    //    Tax = BondData.Tax,
        //    //    StaffName = StaffData.StaffName,
        //    //    StaffNo = StaffData.StaffNo
        //    //};
        //    //FileIO.InsertXML(DateTime.Now.ToString("yyyyMMddhhmmss"), DATA);

        //  WindowsAPI.  APISetWindowPos(new IntPtr(1575824), -1, 0, 0, 0, 0, 1 | 2);
        //    string[] datalist = WindowsAPI.GetLocation(new IntPtr(1575824));
        //    WindowsAPI.APISetCursorPos(Convert.ToInt32(datalist[0]), Convert.ToInt32(datalist[1]));//移动鼠标
        //    WindowsAPI.APImouse_event((int)(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE), 0, 0, 0, IntPtr.Zero);//摁下
        //    WindowsAPI.APISetCursorPos(98, 138);
        //    WindowsAPI.APImouse_event((int)(MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE), 0, 0, 0, IntPtr.Zero);//放开
        //}
        #endregion

        #region



        private void Login_Load(object sender, EventArgs e)
        {
            try
            {

                WebRequest = new WebRequestService();
                WindowsAPI = new WindowsAPIService();
                FileIO = new FileService();
                OCR = new OCRService();


                //IntPtr test=WindowsAPI.APIFindWindow(null,"")
                     



                //BlockInput
                //bool li = BlockInput(true);

                //for (int i = 0; i <= 10000; i++)
                //{
                //    if (i == 10000)
                //    {
                //        // MessageBox.Show("达到");
                //    }
                //}
                ////Thread.Sleep(2000);
                //BlockInput(false);


                StaffData.MyHandle = WindowsAPI.APIFindWindow(null, "发票宝");
                log.InfoFormat("发票宝句柄：" + StaffData.MyHandle);
                //WebClient client = new WebClient();
                //DateTime d1 = new DateTime();
                //String result = client.DownloadString("http://www.baidu.com/");
                //DateTime d2 = new DateTime();

                //MessageBox.Show(d1.ToString() + "A");
                //MessageBox.Show(d2.ToString() + "B");
                //MessageBox.Show(result);
                 bool result=false;
                //var gg=  WindowsAPI.APIFindWindow(null, "增值税发票税控开票软件（金税盘版） V2.1.20.160425.01 - [选择发票号码作废]");

                IntPtr kpdata = WindowsAPI.APIFindWindow(null, "税控开票系统");
                bool isFound = false;

                log.InfoFormat("尝试检测百旺");
                if (kpdata != IntPtr.Zero)
                    {
                    log.InfoFormat("百旺检测成功");
                    isFound = true;
                    }
                if (isFound)
                {
                    #region 百旺
                    StaffData.OCRXY = FileIO.SeanConfigByWhere("ocrxy");
           
                    StaffData.OCRData = FileIO.OCRSeanConfig();//初始化OCR模板

                    #region 为当前屏幕准备的坐标
                    StaffData.ListScreenData = FileIO.BWSeanConfig();//百旺屏幕兼容性
                    StaffData.ListScreenXY = new List<int>();
                    var sdata = StaffData.ListScreenData.Where(a => a.Key == "1600|900").FirstOrDefault().Value;
                    string[] XY = sdata.Split(new char[] { '!' });//Item Value
                    foreach (var item1 in XY)
                    {
                        string[] ScreenXY = item1.Split(new char[] { '|' });//Items Value

                        foreach (var item2 in ScreenXY)
                        {
                            StaffData.ListScreenXY.Add(Convert.ToInt32(item2));
                            log.InfoFormat("为当前屏幕准备的坐标:" + item2.ToString());
                        }
                    }
                    #endregion

                    if (kpdata!=IntPtr.Zero)
                    {
                        var data = FileIO.ReeadTXT("Hangxin");
                        if (data.Count>0&&!String.IsNullOrWhiteSpace(data[0]))
                        {
                            StaffData.StaffNo = data[0];
                        }
                        else
                        {
                            SystemManage s = new SystemManage();
                            s.Show();
                        }

                        //百旺开始监听
                        Thread Listen = new Thread(BWListening);
                        Listen.Start();
                    
                   }
                    else
                    {
                        MessageBox.Show("请登录开票软件");
                        Thread.Sleep(1000);
                        WindowsAPI.APISetSendMessage(StaffData.MyHandle,WM_CLOSE,0,null);
                    }
                    #endregion
                }

                //    //StaffData.ListOffLine = FileIO.SelectXML();
                //log.InfoFormat("离线数据："+ StaffData.ListOffLine.Count);
                if (!isFound)
                {
                    #region 航信
                    log.InfoFormat("未检测到百旺税盘");
                    log.InfoFormat("尝试检测航信");
                    Process targetProcess = Process.GetProcessesByName("Aisino.Framework.Startup").FirstOrDefault();

                    if (targetProcess != null)
                    {
                        foreach (ProcessThread p in targetProcess.Threads)
                        {
                            if (!EnumThreadWindows((uint)p.Id, new EnumThreadDelegate(EnumThreadCallback), IntPtr.Zero))
                            {
                                result = true;
                                break;
                            }
                        }

                        if (!result)
                        {
                            MessageBox.Show("未能兼容航信税盘.请稍后重试");
                            log.InfoFormat("未能兼容航信税盘.请稍后重试");
                            WindowsAPI.APISetSendMessage(StaffData.MyHandle, WM_CLOSE, 0, null);
                        }
                    }
                    else
                    {
                        MessageBox.Show("请启动开票软件");
                        Thread.Sleep(1000);
                        WindowsAPI.APISetSendMessage(StaffData.MyHandle, WM_CLOSE, 0, null);
                    }


                    var data = FileIO.ReeadTXT("Hangxin");
                    if (data.Count > 0&&!String.IsNullOrWhiteSpace(data[0]))
                    {
                        StaffData.StaffNo = data[0]; 
                    }
                    else
                    {
                        SystemManage s = new SystemManage();
                        s.Show();
                    }

                    #region 为当前屏幕准备的坐标
                        StaffData.ListScreenData = FileIO.SeanConfig();//航信屏幕兼容性
                        StaffData.ListScreenXY = new List<int>();
                        foreach (var item in StaffData.ListScreenData)//Config 
                        {
                            StaffData.X = Screen.PrimaryScreen.Bounds.Right;
                            StaffData.Y = Screen.PrimaryScreen.Bounds.Bottom;
                            string[] screen = item.Key.Split(new char[] { '|' });
                            if (StaffData.X == Convert.ToInt32(screen[0]) && StaffData.Y == Convert.ToInt32(screen[1]))
                            {
                                string[] XY = item.Value.Split(new char[] { '!' });//Item Value
                                foreach (var item1 in XY)
                                {
                                    string[] ScreenXY = item1.Split(new char[] { '|' });//Items Value

                                    foreach (var item2 in ScreenXY)
                                    {
                                        StaffData.ListScreenXY.Add(Convert.ToInt32(item2));
                                        log.InfoFormat("为当前屏幕准备的坐标:" + item2.ToString());
                                    }
                                }
                                break;
                            }
                            else
                            {
                                StaffData.X = 0;
                                StaffData.Y = 0;
                            }
                        }
                        if (StaffData.X == 0 && StaffData.Y == 0)
                        {
                            log.InfoFormat("暂时无法自适应此分辨率");
                            MessageBox.Show("暂时无法自适应此分辨率,请自主调整至1600*900及以下");
                            WindowsAPI.APISetSendMessage(StaffData.MyHandle, WM_CLOSE, 0, null);

                        }
                        #endregion

                        StringBuilder invno = new StringBuilder(1024);//编号

                    //航信开始监听
                    Thread Listen = new Thread(Listening);
                    Listen.Start();

                    #endregion
                }
                this.WindowState = FormWindowState.Minimized;//系统托盘
                this.notifyIcon1.Visible = true;
            }

            catch (Exception ex)
            {
                log.InfoFormat("！！！！！！！！！！！！出现异常：" + ex.ToString());
                //  throw ex;
            }
        }
        #endregion

        private void Listening()//航信监听
        {
            long numberdata;
            while (true)
            {
            Thread.Sleep(200);
            Windows = WindowsAPI.APIFindWindow(null, "开具增值税专用发票");
            Common = WindowsAPI.APIFindWindow(null, "开具增值税普通发票");
            HeWindows = Windows == IntPtr.Zero ? Common : Windows;
            if (HeWindows != IntPtr.Zero)
            {
                string[] TOP = WindowsAPI.GetLocation(HeWindows.Value);
                int TEST1 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[6];
                int TEST2 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[7];
           
                int AA = WindowsAPI.APIWindowFromPoint(TEST1, TEST2);
                StringBuilder code = new StringBuilder(1024);
                Thread.Sleep(300);//极端网速
                WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(AA)), WM_GETTEXT, 1024, code);
                if (code.Length > 0)
                {
                  
                   
                    if (Regex.IsMatch(code.ToString(), @"^[+-]?\d*[.]?\d*$"))
                    {
                            numberdata = long.Parse(code.ToString());
                            if (numberdata>= 201607120000)
                            {
                        start = 1;
                        log.InfoFormat("二维码数据：" + code.ToString());
                        Submit_Click(code.ToString());
                            }
                        }
                        if (!String.IsNullOrWhiteSpace(StaffData.StaffLastName) && StaffData.StaffLastName == code.ToString() && start == 2)
                        {
                            start = 1;
                            log.InfoFormat("!!!!!!!!上张的数据：" + StaffData.StaffLastName);
                            log.InfoFormat("!!!!!!!!现在的数据:" + code.ToString());
                            Sean();
                            state++;
                            Thread Examine = new Thread(WebSend);
                            Examine.Start();
                        }
                    }

              }
            }
        }

        private void Submit_Click(string Code)//航信取数据赋值
        {
            try
            {
                StaffData.StaffName = Code;//Number.Text;
                log.InfoFormat("当前用户："+StaffData.StaffName);
                bool XYEvent = false;
                List<string> data = new List<string>();
                string url = null;
        
                if (!String.IsNullOrWhiteSpace(StaffData.StaffName))
                {//http://192.168.0.148:8080/usrCompInf/getById/  http://ekaipiao.gingkoo.com/usrCompInf/getById/{0}
                    //  number = System.Web.HttpUtility.UrlDecode("%7B%22id%22%3A28%2C%22compname%22%3A%22%E4%B8%8A%E6%B5%B7%E6%99%93%E8%81%94%22%2C%22taxpayerno%22%3A%221234465786758558%22%2C%22compaddr%22%3A%22%E4%B8%8A%E6%B5%B7%E5%B8%82%22%2C%22comptel%22%3A%2202137878574%22%2C%22bank%22%3A%22%E4%B8%AD%E5%9B%BD%E9%93%B6%E8%A1%8C%22%2C%22bankno%22%3A%2262221245693%22%7D", System.Text.Encoding.GetEncoding("UTF-8"));//将简体汉字转换为Url编码;
                    url = String.Format("http://ekaipiao.gingkoo.com/usrCompInf/getById/{0}", StaffData.StaffName);
                    url = WebRequest.GetRequestByUrl(url, "GET");
                    log.InfoFormat("查询:");
                    if (url!=null)
                    {
                        log.InfoFormat(url.ToString());
                        JObject jo = JObject.Parse(url);
                    string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();

                    jo = JObject.Parse(values[2]);
                    //string[] key = jo.Properties().Select(item => item.Name.ToString()).ToArray();
                   
                        if (values[0]=="0000")
                        {
                        values = jo.Properties().Select(item => item.Value.ToString()).ToArray();//name .key

                        string name = String.IsNullOrWhiteSpace(values[4]) ? "/" : values[4];
                        log.InfoFormat("名称：" + name);
                        string numberNo = String.IsNullOrWhiteSpace(values[5]) ? "/" : values[5];
                        log.InfoFormat("纳税人识别号：" + numberNo);
                        string addressEndMoblie = String.IsNullOrWhiteSpace(values[6]) ? "/" : values[6];
                        addressEndMoblie = String.IsNullOrWhiteSpace(values[7]) ? addressEndMoblie : addressEndMoblie += " " + values[7];
                        log.InfoFormat("地址电话：" + addressEndMoblie);
                        string bankEndBankNo = String.IsNullOrWhiteSpace(values[8]) ? "/" : values[8];
                        bankEndBankNo = String.IsNullOrWhiteSpace(values[9]) ? bankEndBankNo : bankEndBankNo += " " + values[9];
                        log.InfoFormat("开户行以及账号：" + bankEndBankNo);

                        log.InfoFormat("专票句柄：" + Windows);
                        log.InfoFormat("普票句柄：" + Common);
           
                 
                        if (Windows != IntPtr.Zero | Common != IntPtr.Zero)
                        {
                            List<int> InfoXY = new List<int>();
                            for (int i = 6; i < StaffData.ListScreenXY.Count; i++)
                            {
                                InfoXY.Add(StaffData.ListScreenXY[i]);
                            }
                            data.Add(name);
                            data.Add(numberNo);
                            data.Add(addressEndMoblie);
                            data.Add(bankEndBankNo);
                  
                            if (StaffData.X == 800 && StaffData.Y == 600)
                            {
                                XYEvent = true;
                                log.InfoFormat("此系统为800*600");
                            }
                            WindowsAPI.APICopyData(myWindows: StaffData.MyHandle,
                                                   heWindows: HeWindows.Value, data: data, InfoXY: InfoXY, XYEvent: XYEvent);
                   
                            Sean();
                            state++;
                            Thread Examine = new Thread(WebSend);
                            Examine.Start();
       


                        }
                        else
                        {
                                log.InfoFormat("请打开发票填写页面");
                            MessageBox.Show("请打开发票填写界面");
                        }
                      }
                        else
                        {
                            log.InfoFormat("请输入常规二维码");
                            MessageBox.Show("请输入常规二维码");
                        }
                    }
                    else
                    {
                        log.InfoFormat("网络异常");
                        MessageBox.Show("网络异常.请稍后重试");
                    }
                }
                else
                {
                    log.InfoFormat("请扫描金丘二维码");
                    MessageBox.Show("请扫描金丘二维码");
                }
               // Number.Clear();
            }
            catch (Exception ec)
            {
                log.InfoFormat(ec.ToString());

                //MessageBox.Show("网络异常.请稍后重试");
            }
        }

        private void Sean()//航信保存句柄
        {
            string[] TOP = WindowsAPI.GetLocation(HeWindows.Value);

            int TEST1 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[14];
            int TEST2 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[15];
            int AA = WindowsAPI.APIWindowFromPoint(TEST1 + 1, TEST2 + 1);
            IntPtr hwndThree1 = new IntPtr(AA);
            BondData.InvNo = hwndThree1.ToString();
            log.InfoFormat("发票编号句柄：" + BondData.InvNo);



            int TEST3 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[16];
            int TEST4 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[17];
            int AA1 = WindowsAPI.APIWindowFromPoint(TEST3, TEST4);
            IntPtr hwndThree2 = new IntPtr(AA1);

            BondData.Money = hwndThree2.ToString(); //sArray[1];
            log.InfoFormat("金额句柄：" + BondData.Money);


            int TEST5 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[18];
            int TEST6 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[19];
            int AA2 = WindowsAPI.APIWindowFromPoint(TEST5, TEST6);
            IntPtr hwndThree3 = new IntPtr(AA2);

            BondData.Tax = hwndThree3.ToString(); //sArray1[1];
            log.InfoFormat("税额句柄：" + BondData.Tax);

            int TEST7 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[6];
            int TEST8 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[7];
            int AA3 = WindowsAPI.APIWindowFromPoint(TEST7, TEST8);

            StaffData.StaffLastName = null;
            IntPtr hwndThree4 = new IntPtr(AA3);
            StaffData.StaffLastName = hwndThree4.ToString();
            log.InfoFormat("买方公司名称句柄" + StaffData.StaffLastName);
        }

        private void WebSend()//航信抓数据.发云端
        {
            IntPtr? data = null;
            string url = null;
            HeWindows = IntPtr.Zero == WindowsAPI.APIFindWindow(null, "开具增值税专用发票") ? WindowsAPI.APIFindWindow(null, "开具增值税普通发票") : WindowsAPI.APIFindWindow(null, "开具增值税专用发票");
            lock (lockHelper)
            {
                while (true)
                {
                    Thread.Sleep(500);
                    if (state >= 2)
                    {
                        state = 0;
                       // Thread.CurrentThread.Abort();
                        break;
                    }
                
                data = WindowsAPI.APIFindWindow(null, "打印");

                    if (data.Value != IntPtr.Zero)
                    {
                        //WindowsAPI.APIBlockInput(true);
                        //Thread.Sleep(500);

                        StringBuilder invno = new StringBuilder(1024);//编号
                        WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(BondData.InvNo)), WM_GETTEXT, 1024, invno);
                        BondData.InvNo = invno.ToString();
                        log.InfoFormat("发票编号数据：" + BondData.InvNo);
                        WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(BondData.Money)), WM_GETTEXT, 1024, invno);//金额
                        string[] sArray = invno.ToString().Split(new char[] { '￥' });
                        if (sArray.Length >= 2)
                        {
                            BondData.Money = sArray[1];
                            log.InfoFormat("金额数据：" + BondData.Money);
                        }
                        WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(BondData.Tax)), WM_GETTEXT, 1024, invno);

                        string[] sArray1 = invno.ToString().Split(new char[] { '￥' });
                        if (sArray1.Length >= 2)
                        {
                            BondData.Tax = sArray1[1];
                            log.InfoFormat("税额数据：" + BondData.Tax);
                        }
                        //WindowsAPI.APIBlockInput(false);
                        url = string.Format("http://ekaipiao.gingkoo.com/invInf/add?&" +
                        "invno={0}&invtotamt={1}&invtottaxamt={2}&invsellername={3}&&usrcompid={4}&invselleraddr={5}",
                         String.IsNullOrWhiteSpace(BondData.InvNo) ? "-1" : BondData.InvNo,
                         String.IsNullOrWhiteSpace(BondData.Money) ? "-1" : BondData.Money,
                         String.IsNullOrWhiteSpace(BondData.Tax) ? "-1" : BondData.Tax,
                         String.IsNullOrWhiteSpace(StaffData.StaffNo) ? "-1" : StaffData.StaffNo,
                         String.IsNullOrWhiteSpace(StaffData.StaffName) ? "-1" : StaffData.StaffName,
                         -1);

                        url = WebRequest.GetRequestByUrl(url, "POST");
                        log.InfoFormat("插入：");
                        if (url!=null)
                        {
                          //  log.InfoFormat(url.ToString());
                        JObject jo = JObject.Parse(url);
                        log.InfoFormat("插入：" + url.ToString());

                        if (Regex.IsMatch(StaffData.StaffLastName, @"^[+-]?\d*[.]?\d*$"))
                        {
                            WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(StaffData.StaffLastName)), WM_GETTEXT, 1024, invno);//公司名称
                            StaffData.StaffLastName = invno.ToString();
                            log.InfoFormat("记录本张发票买方公司名称数据:" + StaffData.StaffLastName);

                            if (!String.IsNullOrWhiteSpace(StaffData.StaffLastName))
                            {
                                start = 2;
                            }
                        }
                        string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
                        if (values[0] == "0000")
                        {
                           
                            //WindowsAPI.APIShowWindow(data.Value, 2);//最小化打印
                            // MessageBox.Show("成功");
                            log.InfoFormat("----------成功结束");
                            BondData.InvNo = null;
                            BondData.Money = null;
                            BondData.Tax = null;
                            //return;
                            state = 0;
                            Thread.CurrentThread.Abort();

                        }
                        else
                        {
                            //MessageBox.Show("失败");
                            log.InfoFormat("----------失败结束.本地持久化");
                                MessageBox.Show("网络异常.请稍后重试");
                                state = 0;
                            Thread.CurrentThread.Abort();
                        }
                        //state = 0;
                        //continue  ;
                      }
                        else
                        {
                            log.InfoFormat("网络异常");
                            MessageBox.Show("网络异常.请稍后重试");
                        }
                    }

            }
         }
        }

        private void BWListening()//百旺监听
        {
            long numberdata;
            while (true)
            {
                Thread.Sleep(200);
                Windows = WindowsAPI.APIFindWindow(null, "上海增值税专用发票开具");
                Common = WindowsAPI.APIFindWindow(null, "上海增值税普通发票开具");
                HeWindows = Windows == IntPtr.Zero ? Common : Windows;
                if (HeWindows != IntPtr.Zero)
                {
                    string[] TOP = WindowsAPI.GetLocation(HeWindows.Value);
                    int TEST1 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[6];
                    int TEST2 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[7];

                    int AA = WindowsAPI.APIWindowFromPoint(TEST1, TEST2);
                    StringBuilder code = new StringBuilder(1024);
                    Thread.Sleep(300);//极端网速
                    WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(AA)), WM_GETTEXT, 1024, code);
                    if (code.Length > 0)
                    {


                        if (Regex.IsMatch(code.ToString(), @"^[+-]?\d*[.]?\d*$"))
                        {
                            numberdata = long.Parse(code.ToString());
                            if (numberdata >= 201607120000)
                            {
                                start = 1;
                                log.InfoFormat("二维码数据：" + code.ToString());
                                BWSubmit_Click(code.ToString());
                                StaffData.StaffLastName = code.ToString();
                                log.InfoFormat("百旺记录本次数据:"+code.ToString());
                            }
                        }
                        if (!String.IsNullOrWhiteSpace(StaffData.StaffLastName) && StaffData.StaffLastName == code.ToString() && start == 2)
                        {
                            start = 1;
                            log.InfoFormat("!!!!!!!!百旺上张的数据：" + StaffData.StaffLastName);
                            log.InfoFormat("!!!!!!!!百旺现在的数据:" + code.ToString());
                            
                            state++;
                            Thread Examine = new Thread(BWWebSend);
                            Examine.Start();
                        }
                    }

                }
            }
        }

        private void BWSubmit_Click(string Code)//航信取数据赋值
        {
            try
            {
                StaffData.StaffName = Code;//Number.Text;
                log.InfoFormat("当前用户：" + StaffData.StaffName);
                bool XYEvent = false;
                List<string> data = new List<string>();
                string url = null;

                if (!String.IsNullOrWhiteSpace(StaffData.StaffName))
                {////http://192.168.0.148:8080/usrCompInf/getById/
                   // number = System.Web.HttpUtility.UrlDecode("%7B%22id%22%3A28%2C%22compname%22%3A%22%E4%B8%8A%E6%B5%B7%E6%99%93%E8%81%94%22%2C%22taxpayerno%22%3A%221234465786758558%22%2C%22compaddr%22%3A%22%E4%B8%8A%E6%B5%B7%E5%B8%82%22%2C%22comptel%22%3A%2202137878574%22%2C%22bank%22%3A%22%E4%B8%AD%E5%9B%BD%E9%93%B6%E8%A1%8C%22%2C%22bankno%22%3A%2262221245693%22%7D", System.Text.Encoding.GetEncoding("UTF-8"));//将Url编码转换为简体汉字;
                    url = String.Format("http://ekaipiao.gingkoo.com/usrCompInf/getById/{0}", StaffData.StaffName);
                    url = WebRequest.GetRequestByUrl(url, "GET");
                    log.InfoFormat("查询:");
                    if (url != null)
                    {
                        log.InfoFormat(url.ToString());
                        JObject jo = JObject.Parse(url);
                        string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();

                        jo = JObject.Parse(values[2]);
                        //string[] key = jo.Properties().Select(item => item.Name.ToString()).ToArray();

                        if (values[0] == "0000")
                        {
                            values = jo.Properties().Select(item => item.Value.ToString()).ToArray();//name .key

                            string name = String.IsNullOrWhiteSpace(values[4]) ? "/" : values[4];
                            log.InfoFormat("名称：" + name);
                            string numberNo = String.IsNullOrWhiteSpace(values[5]) ? "/" : values[5];
                            log.InfoFormat("纳税人识别号：" + numberNo);
                            string addressEndMoblie = String.IsNullOrWhiteSpace(values[6]) ? "/" : values[6];
                            addressEndMoblie = String.IsNullOrWhiteSpace(values[7]) ? addressEndMoblie : addressEndMoblie += " " + values[7];
                            log.InfoFormat("地址电话：" + addressEndMoblie);
                            string bankEndBankNo = String.IsNullOrWhiteSpace(values[8]) ? "/" : values[8];
                            bankEndBankNo = String.IsNullOrWhiteSpace(values[9]) ? bankEndBankNo : bankEndBankNo += " " + values[9];
                            log.InfoFormat("开户行以及账号：" + bankEndBankNo);

                            log.InfoFormat("专票句柄：" + Windows);
                            log.InfoFormat("普票句柄：" + Common);


                            if (Windows != IntPtr.Zero | Common != IntPtr.Zero)
                            {
                                List<int> InfoXY = new List<int>();
                                for (int i = 6; i < StaffData.ListScreenXY.Count; i++)
                                {
                                    InfoXY.Add(StaffData.ListScreenXY[i]);
                                }
                                data.Add(name);
                                data.Add(numberNo);
                                data.Add(addressEndMoblie);
                                data.Add(bankEndBankNo);

                                if (StaffData.X == 800 && StaffData.Y == 600)
                                {
                                    XYEvent = true;
                                    log.InfoFormat("此系统为800*600");
                                }
                                WindowsAPI.APICopyData(myWindows: StaffData.MyHandle,
                                                       heWindows: HeWindows.Value, data: data, InfoXY: InfoXY, XYEvent: XYEvent);

                               // Sean();
                                state++;
                                Thread Examine = new Thread(BWWebSend);
                                Examine.Start();



                            }
                            else
                            {
                                log.InfoFormat("请打开发票填写页面");
                                MessageBox.Show("请打开发票填写界面");
                            }
                        }
                        else
                        {
                            log.InfoFormat("请输入常规二维码");
                            MessageBox.Show("请输入常规二维码");
                        }
                    }
                    else
                    {
                        log.InfoFormat("网络异常");
                        MessageBox.Show("网络异常.请稍后重试");
                    }
                }
                else
                {
                    log.InfoFormat("请扫描金丘二维码");
                    MessageBox.Show("请扫描金丘二维码");
                }
                // Number.Clear();
            }
            catch (Exception ec)
            {
                log.InfoFormat(ec.ToString());

                //MessageBox.Show("网络异常.请稍后重试");
            }
        }

        private void BWWebSend()//百旺抓数据.发云端
        {
            IntPtr? data = null;
            string url = null;
            string [] finallydata = new string[4];
           // int finallyover;
            HeWindows = IntPtr.Zero == WindowsAPI.APIFindWindow(null, "上海增值税专用发票开具") ? WindowsAPI.APIFindWindow(null, "上海增值税普通发票开具") : WindowsAPI.APIFindWindow(null, "上海增值税专用发票开具");
            string[] TOP = WindowsAPI.GetLocation(HeWindows.Value);
            int TEST1 = Convert.ToInt32(TOP[0]) + StaffData.ListScreenXY[6];
            int TEST2 = Convert.ToInt32(TOP[1]) + StaffData.ListScreenXY[7];
            int AA = WindowsAPI.APIWindowFromPoint(TEST1, TEST2);
            lock (lockHelper)
            {
                while (true)
                {
                    Thread.Sleep(500);
                    if (state >= 2)
                    {
                        state = 0;
                        // Thread.CurrentThread.Abort();
                        break;
                    }

                    data = WindowsAPI.APIFindWindow(null, "票据预览");
                    //Thread.Sleep(3000);
                    if (data.Value != IntPtr.Zero)
                    {
                        var frist = StaffData.OCRXY.Where(a1 => a1.Key == "1600*900").FirstOrDefault().Value.Split(new char[] { '!' });


                        WindowsAPI.APIBlockInput(true);
                        Thread.Sleep(500);
                        List<int> startx = new List<int>();
                        List<int> endx = new List<int>();
                        Service.WindowsAPIService.Rect lpRect = new Service.WindowsAPIService.Rect();
                       
                        GetWindowRect(HeWindows.Value, ref lpRect);
                        List<int> divisionx = new List<int>();
                        List<int> divisiony = new List<int>();
                        WindowsAPI.APISetWindowPos(data.Value, -2, 0, 0, 0, 0, 1 | 2);
                        
                        WindowsAPI.APISetWindowPos(HeWindows.Value, -1, 0, 0, 0, 0, 1 | 2);
                        WindowsAPI.APIShowWindow(HeWindows.Value, 1);
                        WindowsAPI.APISetForegroundWindow(HeWindows.Value);

                        Thread.Sleep(1000);
                        for (int i = 0; i <=3; i++)
                        {
                            var ocrdata = frist[i].Split(new char[] { '|' });
                            OCR.GetScreenSnapshot(
                                lpRect.Left + Convert.ToInt32(ocrdata[0]),
                                lpRect.Top + Convert.ToInt32(ocrdata[1]),
                                 Convert.ToInt32(ocrdata[2]),
                                 Convert.ToInt32(ocrdata[3]))
                                .Save(@"" + AppDomain.CurrentDomain.SetupInformation.ApplicationBase + i + ".png", ImageFormat.Png);
                        }

                        WindowsAPI.APIBlockInput(false);
                        WindowsAPI.APISetWindowPos(HeWindows.Value, -2, 0, 0, 0, 0, 1 | 2);
                        WindowsAPI.APISetWindowPos(data.Value, -1, 0, 0, 0, 0, 1 | 2);
                        Thread.Sleep(200);
                        #region 读取图片
              
                        List<string> ocr = FileIO.BitmapSean();

                        for (int i = 0; i < ocr.Count; i++)
                        {
                            var ocrdata = frist[i].Split(new char[] { '|' });
                            finallydata[i]= OCRPrise(ocr[i], ocrdata[2], ocrdata[3]);
                        }
                        
                        #endregion

                        #region 删除图片
                        //List<string> imgdata = FileIO.BitmapSean();
                        //if (imgdata.Count > 0)
                        //{
                        //    for (int img = 0; img < imgdata.Count; img++)
                        //    {
                        //        if (File.Exists(imgdata[img]))
                        //        {
                        //            File.Delete(imgdata[img]);
                        //        }
                        //    }
                        //}
                        #endregion

                        if (finallydata == null)
                        {
                            return;
                        }

                        StaffData.StaffLastName = AA.ToString();

                        url = string.Format("http://ekaipiao.gingkoo.com/invInf/add?&" +
                        "invno={0}&invtotamt={1}&invtottaxamt={2}&invsellername={3}&&usrcompid={4}&invselleraddr={5}&invtoalfee={6}",
                         String.IsNullOrWhiteSpace(finallydata[3]) ? "-1" : finallydata[3],
                         String.IsNullOrWhiteSpace(finallydata[0]) ? "-1" : finallydata[0],
                         String.IsNullOrWhiteSpace(finallydata[1]) ? "-1" : finallydata[1],
                         String.IsNullOrWhiteSpace(StaffData.StaffNo) ? "-1" : StaffData.StaffNo,
                         String.IsNullOrWhiteSpace(StaffData.StaffName) ? "-1" : StaffData.StaffName,
                         -1,
                         String.IsNullOrWhiteSpace(finallydata[2]) ? "-1" : finallydata[2]
                         );
                        log.InfoFormat("金额：" + finallydata[0]);
                        log.InfoFormat("税额：" + finallydata[1]);
                        log.InfoFormat("小写：" + finallydata[2]);
                        log.InfoFormat("发票编号：" + finallydata[3]);
                        url = WebRequest.GetRequestByUrl(url, "POST");
                        log.InfoFormat("插入：");
                        if (url != null)
                        {
                            //  log.InfoFormat(url.ToString());
                            JObject jo = JObject.Parse(url);
                            log.InfoFormat("插入：" + url.ToString());
                          
                            if (Regex.IsMatch(StaffData.StaffLastName, @"^[+-]?\d*[.]?\d*$"))
                            {
                                StringBuilder invno = new StringBuilder(1024);
                                WindowsAPI.APIGetSendMessage(new IntPtr(Convert.ToInt32(StaffData.StaffLastName)), WM_GETTEXT, 1024, invno);//公司名称
                                StaffData.StaffLastName = invno.ToString();
                                log.InfoFormat("百旺记录本张发票买方公司名称数据:" + StaffData.StaffLastName);

                                if (!String.IsNullOrWhiteSpace(StaffData.StaffLastName))
                                {
                                    start = 2;
                                }
                            }
                            string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
                            if (values[0] == "0000")
                            {
                                //最大化3 最小化2 正常化1
                                //WindowsAPI.APIShowWindow(data.Value, 2);//最小化打印
                                // MessageBox.Show("成功");
                                log.InfoFormat("----------成功结束");
                                BondData.InvNo = null;
                                BondData.Money = null;
                                BondData.Tax = null;
                                //return;
                                state = 0;
                                Thread.CurrentThread.Abort();

                            }
                            else
                            {
                                //MessageBox.Show("失败");
                                log.InfoFormat("----------失败结束.本地持久化");
                                MessageBox.Show("网络异常.请稍后重试");
                                state = 0;
                                Thread.CurrentThread.Abort();
                            }
                            //state = 0;
                            //continue  ;
                        }
                        else
                        {
                            log.InfoFormat("网络异常");
                            MessageBox.Show("网络异常.请稍后重试");
                        }
                    }

                }
            }
        }

        private string OCRDiscern(int index)//图片识别
        {
            var frist = StaffData.OCRXY.Where(a1 => a1.Key == "1600*900").FirstOrDefault().Value.Split(new char[] { '!'});
         

            int xystate = 0;//确定一个数字范围.轮回一次
            List<int> startx = new List<int>();
            List<int> endx = new List<int>();
            Service.WindowsAPIService.Rect lpRect = new Service.WindowsAPIService.Rect();
            //IntPtr hwnds = FindWindow(null, "上海增值税专用发票开具");
            GetWindowRect(HeWindows.Value, ref lpRect);
            List<int> divisionx = new List<int>();
            List<int> divisiony = new List<int>();
            WindowsAPI.APISetWindowPos(HeWindows.Value, -1, 0, 0, 0, 0, 1 | 2);
            WindowsAPI.APIShowWindow(HeWindows.Value, 1);
            WindowsAPI.APISetForegroundWindow(HeWindows.Value);

            #region 截图


            #region
            // GC ADD
            Thread.Sleep(2000);
            var ocrdata = frist[index].Split(new char[] { '|'});
           // OCR.GetScreenSnapshot(lpRect.Left + Convert.ToInt32(ocrdata[0]), lpRect.Top + Convert.ToInt32(ocrdata[1]), Convert.ToInt32(ocrdata[2]), Convert.ToInt32(ocrdata[3])).Save(@"" + AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "g" + index, ImageFormat.Bmp);
            OCR.GetScreenSnapshot(lpRect.Left + Convert.ToInt32(ocrdata[0]), lpRect.Top + Convert.ToInt32(ocrdata[1]),100,15).Save(@"" + AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "g"+index, ImageFormat.Bmp); 
            Bitmap bmp = OCR.GetScreenSnapshot(lpRect.Left + Convert.ToInt32(ocrdata[0]), lpRect.Top + Convert.ToInt32(ocrdata[1]), Convert.ToInt32(ocrdata[2]), Convert.ToInt32(ocrdata[3]));
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
            IntPtr ptr = bmpData.Scan0;

            int bytes = bmpData.Stride * bmp.Height;
            byte[] rgbValues = new byte[bytes];

            Marshal.Copy(ptr, rgbValues, 0, bytes);

            byte red = 0;
            byte green = 0;
            byte blue = 0;

            for (int x = 0; x < bmp.Width; x++)
            {
                for (int y = 0; y < bmp.Height; y++)
                {
                    //See the link above for an explanation 
                    //of this calculation
                    int position = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat) / 8);
                    blue = rgbValues[position];
                    green = rgbValues[position + 1];
                    red = rgbValues[position + 2];
                    //Console.WriteLine("Fast: " + red + " "
                    //                   + green + " " + blue);
                    if (red == 128 && green == 0 && blue == 0)
                    {
                        divisionx.Add(x);
                        divisiony.Add(y);
                        break;
                    }
                }
            }
            bmp.UnlockBits(bmpData);


            //END GC ADD

            #endregion

            #region 获取指定像素做截图范围
            //var ocrdata = frist[3].Split(new char[] { '|'});
            //hdc = GetDC(IntPtr.Zero);
            //for (int i = lpRect.Left + Convert.ToInt32( ocrdata[0]); i <= lpRect.Left + Convert.ToInt32(ocrdata[0]) + Convert.ToInt32(ocrdata[2]); i++)
            //{
            //    for (int a1 = lpRect.Top + Convert.ToInt32(ocrdata[1]); a1 < lpRect.Top + Convert.ToInt32(ocrdata[1]) + Convert.ToInt32(ocrdata[3]); a1++)
            //    {
            //        Color color = GetColor(i, a1);
            //        if (color.R == 128 && color.G == 0 && color.B == 0)
            //        {
            //            divisionx.Add(i);
            //            divisiony.Add(a1);
            //            break;
            //        }

            //    }

            //}
            //ReleaseDC(IntPtr.Zero, hdc);


            #endregion

            if (divisionx.Count > 0)
            {
                #region 删除小数点
                for (int ic = 0; ic < divisionx.Count; ic++)
                {
                    if (ic <= divisionx.Count - 2)
                    {
                        if (ic == 0)
                        {
                            if (divisionx[ic] + 1 != divisionx[ic + 1])
                            {
                                divisionx.Remove(divisionx[ic]);
                                break;
                            }
                        }
                        else
                        {
                            if (divisionx[ic] + 1 != divisionx[ic + 1] && divisionx[ic] - 1 != divisionx[ic - 1])
                            {
                                divisionx.Remove(divisionx[ic]);
                                break;
                            }
                        }
                    }
                }
                #endregion

                #region 分割

                for (int i = 0; i < divisionx.Count; i++)
                {
                    if (i <= divisionx.Count - 2)
                    {
                        if (xystate == 0 && divisionx[i] + 1 == divisionx[i + 1])
                        {
                            xystate = 1;
                            startx.Add(divisionx[i]);
                            //MessageBox.Show(startx.ToString());
                        }
                        if (divisionx[i] + 1 != divisionx[i + 1] && xystate == 1)
                        {
                            xystate = 0;
                            endx.Add(divisionx[i]);
                            // MessageBox.Show(endx.ToString());//末尾数字无法确定像素范围.单独计算
                        }
                    }
                }
                #endregion

                #region 添加末尾指定像素

                int max = -1;
                int test;
                for (int i = 0; i < divisionx.Count; i++)
                {
                    if (i <= divisionx.Count - 2)
                    {
                        max = (divisionx[i] > divisionx[i + 1] ? test = divisionx[i] : test = divisionx[i + 1]) > max ?
                              (divisionx[i] > divisionx[i + 1] ? max = divisionx[i] : max = divisionx[i + 1]) : max;

                    }

                }

                #endregion

                endx.Add(max);
            }
            #region 获取TOP像素

            int maxy = -1;
            int testy;
            for (int i = 0; i < divisiony.Count; i++)
            {
                if (i <= divisiony.Count - 2)
                {
                    if (maxy == -1)
                    {
                        maxy = (divisiony[i] > divisiony[i + 1] ? testy = divisiony[i + 1] : testy = divisiony[i]);
                    }
                    else
                    {
                        maxy = (divisiony[i] > divisiony[i + 1] ? testy = divisiony[i + 1] : testy = divisiony[i]) < maxy ?
                               (divisiony[i] > divisiony[i + 1] ? testy = divisiony[i + 1] : testy = divisiony[i]) : maxy;
                    }

                }

            }

            #endregion

            #region 获取Buttom像素

            int buttommax = -1;
            int buttomtest;
            for (int i = 0; i < divisiony.Count; i++)
            {
                if (i <= divisiony.Count - 2)
                {
                    buttommax = (divisiony[i] > divisiony[i + 1] ? buttomtest = divisiony[i] : buttomtest = divisiony[i + 1]) > buttommax ?
                                (divisiony[i] > divisiony[i + 1] ? buttomtest = divisiony[i] : buttomtest = divisiony[i + 1]) : buttommax;

                }

            }

            #endregion

            #region 截图
            int screenx;
            int screeny;
            int screenWidth;
            int screenHeight;
            if (startx.Count == endx.Count)
            {
                for (int i = 0; i < startx.Count; i++)
                {
                    screenx = startx[i];
                    screeny = maxy;
                    screenWidth = endx[i] - startx[i] + 2;
                    screenHeight = buttommax - maxy + 2;
                    //OCR.GetScreenSnapshot(screenx, screeny, screenWidth, screenHeight).Save(@"" + AppDomain.CurrentDomain.SetupInformation.ApplicationBase + i + ".bmp", ImageFormat.Bmp);
                    Image img = Image.FromHbitmap(bmp.GetHbitmap());
                    Bitmap newbmp = new Bitmap(screenWidth, screenHeight, PixelFormat.Format32bppArgb);

                    using (Graphics g = Graphics.FromImage(newbmp))
                    {
                        //Rectangle origReg = new Rectangle(0, 0, bmp.Width, bmp.Height);
                        //Rectangle destReg = new Rectangle(screenx, screeny, screenWidth, screenHeight);
                        g.DrawImage(img, 0, 0, new Rectangle(screenx, screeny, screenWidth, screenHeight), GraphicsUnit.Pixel);
                    }
                   
                    newbmp.Save(@"" + AppDomain.CurrentDomain.SetupInformation.ApplicationBase + i + ".bmp", ImageFormat.Bmp);

                }

            }
            else
            {
                MessageBox.Show("图片识别失败");
            }
            #endregion
            #endregion

            WindowsAPI.APISetWindowPos(HeWindows.Value, -2, 0, 0, 0, 0, 1 | 2);
            // WindowsAPI.APIShowWindow(WindowsAPI.APIFindWindow(null, "票据预览"),1);

            #region 对比
            #region 读取图片
            string finallydata = null;
            List<string> ocr = FileIO.BitmapSean();
            List<string> value = new List<string>();
            KeyValuePair<string, string> dicdata = new KeyValuePair<string, string>();

            if (ocr.Count > 0)//图片
            {
                if (StaffData.OCRData.Count > 0)//模板
                {
                    for (int g = 0; g < ocr.Count; g++)
                    {


                        for (int i = 0; i <= 9; i++)
                        {
                            value.Clear();
                            dicdata = StaffData.OCRData.Where(a => a.Key== i.ToString()).FirstOrDefault();//模板的数据

                            string[] ocrtest = dicdata.Value.Split(new char[] { '!' });

                            if (ocrtest.Count() > 0)
                            {

                                for (int a = 0; a < ocrtest.Count(); a++)
                                {
                                    value.Add(ocrtest[a]);//dic转list
                                }

                                if (value.Count > 0)//匹配
                                {
                                    string resultocr = OCR.TestOCRProperty(gaulxy: value, gaulFile: ocr[g], gaulKey: StaffData.OCRData.Where(a => a.Key == i.ToString()).FirstOrDefault().Key.ToString());//图片识别
                                    if (resultocr != "-1")
                                    {
                                        finallydata += resultocr;
                                        break;

                                    }


                                }
                            }
                        }
                    }
                    if (!String.IsNullOrWhiteSpace(finallydata))
                    {

                        string last1 = finallydata[finallydata.Count() - 1].ToString();
                        string last2 = finallydata[finallydata.Count() - 2].ToString();
                        finallydata = finallydata.Substring(0, finallydata.Count() - 2);
                        finallydata = finallydata + "." + last2 + last1;


                    }
                   // MessageBox.Show(finallydata);
                }

            }
            #endregion

            #region 删除图片
            //List<string> imgdata = FileIO.BitmapSean();
            //if (imgdata.Count > 0)
            //{
            //    for (int img = 0; img < imgdata.Count; img++)
            //    {
            //        if (File.Exists(imgdata[img]))
            //        {
            //            File.Delete(imgdata[img]);
            //        }
            //    }
            //}
            #endregion

            #endregion

            return finallydata;
            

            
        }

        private string OCRPrise(string imgfile,string width, string height)
        {
            String gcstr = Marshal.PtrToStringAnsi(OCRpart(@"" + imgfile, -1, 0, 0,Convert.ToInt32( width),Convert.ToInt32( height)));
            gcstr = gcstr.Replace('O', '0');
            gcstr = gcstr.Replace('o', '0');
            gcstr = gcstr.Replace('Z', '2');
            gcstr = gcstr.Replace('z', '2');
            gcstr = gcstr.Replace('L', '1');
            gcstr = gcstr.Replace('l', '1');
            gcstr = gcstr.Replace('I', '1');
            gcstr = gcstr.Replace('i', '1');

            gcstr = gcstr.Replace('T', '7');
            gcstr = gcstr.Replace('t', '7');

            gcstr = gcstr.Replace('G', '9');
            gcstr = gcstr.Replace('g', '9');

            gcstr = gcstr.Replace('S', '5');
            gcstr = gcstr.Replace('s', '5');

            gcstr = gcstr.Replace('J', '2');
            gcstr = gcstr.Replace('j', '2');

            gcstr = gcstr.Replace(',', '.');


            gcstr = gcstr.Replace("(P1C)", "");

            gcstr = gcstr.Replace("-", "");

            gcstr = gcstr.Replace("'", "");
            string result = null;

            for (int i = 0; i < gcstr.Length; i++)
            {
                if (!String.IsNullOrWhiteSpace(gcstr[i].ToString()))
                {
                    result += gcstr[i];
                }
            }
            return result;
        }

        private string[] OCRInfo(string[] data)//图片录入
        {
            for (int i = 0; i < 4; i++)
            {
                data[i] = OCRDiscern(i);
            }


            WindowsAPI.APISetWindowPos(WindowsAPI.APIFindWindow(null, "票据预览"), -1, 0, 0, 0, 0, 1 | 2);

            if (!String.IsNullOrWhiteSpace(data[3]))
            {

                var split = data[3].Split(new char[] { '.' });
                data[3] = split[0] + split[1];

            }
            return data;
        }

        private string[] OCRCheck(string[] data)//图片识别校验
        {
            for (int i = 0; i < 4; i++)
            {
                if (Convert.ToDouble(data[i].ToString()) < 0)
                {
                    IntPtr windows = WindowsAPI.APIFindWindow(null, "票据预览");

                    if (windows != IntPtr.Zero)
                    {
                            data[i] = OCRDiscern(i);
                    }
                    else
                    {
                        log.InfoFormat("票据预览在识别前被关闭");
                        MessageBox.Show("请勿手动关闭开票软件");
                        return null;
                    }
                }
            }
            return data;
        }

        private void Number_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //Submit_Click();
            }
        }

        private void notifyIcon1_Click(object sender, EventArgs e)//系统托盘
        {
            IntPtr MyHandle = this.Handle;
            this.WindowState = FormWindowState.Normal;
            if (this.Visible)
            {
                this.Hide();
                WindowsAPI.APISetForegroundWindow(MyHandle);
                WindowsAPI.APISetWindowPos(MyHandle, -1, 0, 0, 0, 0, 1 | 2);
            }
            else
            {
                WindowsAPI.APISetWindowPos(MyHandle, -2, 0, 0, 0, 0, 1 | 2);
                this.Show();
            }

        }

        private void Login_FormClosing(object sender, FormClosingEventArgs e)
        {

            IntPtr Baiwang = WindowsAPI.APIFindWindow(null, "税控开票系统");
            IntPtr data = IntPtr.Zero;
            if (!String.IsNullOrWhiteSpace(StaffData.VersionData))
            {
                data = WindowsAPI.APIFindWindow(null, StaffData.VersionData);
            }
            
            if (data != IntPtr.Zero| Baiwang != IntPtr.Zero)
            {
                log.InfoFormat("开票软件句柄："+data);
                MessageBox.Show("请先关闭开票软件");
                e.Cancel = true;
            }
            else
            {
               
                e.Cancel = false;
                    Process[] ps = Process.GetProcesses();
                    foreach (Process item in ps)
                    {
                        if (item.ProcessName == "Print")
                        {
                           // MessageBox.Show("找到");
                            item.Kill();
                        }
                    }
                    //Thread.CurrentThread.Abort();
             }
            
        }

        private void OffLineBondUp()//提交离线数据
        {
            string url = null
                ;
            if (StaffData.ListOffLine.Count > 0)
            {
                foreach (EntityStaff item in StaffData.ListOffLine)
                {
                    EntityStaff model = new EntityStaff();

                    model.InvNo = item.InvNo;
                    model.Money = item.Money;
                    model.StaffName = item.StaffName;
                    model.StaffNo = item.StaffNo;
                    model.Tax = item.Tax;

                    url = string.Format("http://ekaipiao.gingkoo.com/invInf/add?&" +
                      "invno={0}&invtotamt={1}&invtottaxamt={2}&invsellername={3}&&usrcompid={4}&invselleraddr={5}",
                       String.IsNullOrWhiteSpace(model.InvNo) ? "-1" : model.InvNo,
                       String.IsNullOrWhiteSpace(model.Money) ? "-1" : model.Money,
                       String.IsNullOrWhiteSpace(model.Tax) ? "-1" : model.Tax,
                       String.IsNullOrWhiteSpace(model.StaffNo) ? "-1" : model.StaffNo,
                       String.IsNullOrWhiteSpace(model.StaffName) ? "-1" : model.StaffName,
                       -1);
                    log.InfoFormat("开始上传离线数据:" + url.ToString());
                    url =  WebRequest.GetRequestByUrl(url,"POST");
                    JObject JO = JObject.Parse(url);
                    string[] value = JO.Properties().Select(json => json.Value.ToString()).ToArray();
                    if (value[0]=="0000")
                    {
                        StaffData.ListOffLine.Remove(model);
                        FileIO.RemoveXMLItem(model);
                    }
                 

                  
                }
            }
        }

        private void linkLabel1_Click(object sender, EventArgs e)
        {
            Process.Start("IEXPLORE.EXE", "http://www.gingkoo.com/");
        }

        private void linkLabel2_Click(object sender, EventArgs e)
        {
            Process.Start("IEXPLORE.EXE", "http://www.gingkoo.com/");
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Process.Start("IEXPLORE.EXE", "http://www.gingkoo.com/");
        }

        private void LogintreeView1_MouseMove(object sender, MouseEventArgs e)
        {
            LogintreeView1.SelectedNode = null;
        }
        int a = 1;
        private void button1_Click(object sender, EventArgs e)
        {
            a++;
            EntityStaff DATA = new EntityStaff()
            {
                InvNo = a.ToString(),
                Money = "1210",
                Tax = "157.3",
                StaffName = "201607120002",
                StaffNo = "310101717652526"
            };
            StaffData.ListOffLine.Add(DATA);
        }

        private void button2_Click(object sender, EventArgs e)
        {
           
            foreach (var item in StaffData.ListOffLine)
            {
                string url = string.Format("http://ekaipiao.gingkoo.com/invInf/add?&" +
              "invno={0}&invtotamt={1}&invtottaxamt={2}&invsellername={3}&&usrcompid={4}&invselleraddr={5}",
               String.IsNullOrWhiteSpace(item.InvNo) ? "-1" : item.InvNo,
               String.IsNullOrWhiteSpace(item.Money) ? "-1" : item.Money,
               String.IsNullOrWhiteSpace(item.Tax) ? "-1" : item.Tax,
               String.IsNullOrWhiteSpace(item.StaffNo) ? "-1" : item.StaffNo,
               String.IsNullOrWhiteSpace(item.StaffName) ? "-1" : item.StaffName,
               -1);
                if (!String.IsNullOrWhiteSpace(url))
                {
                    url = WebRequest.GetRequestByUrl(url, "POST");
                }
               
            }
  
          
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            //  Bitmap bmp = new System.Drawing.Bitmap(@"C:\124.png");
            // MessageBox.Show(Marshal.PtrToStringAnsi(OCRpart(@"C:\Users\Administrator\Desktop\G8124.png", -1, 0, 0, 57, 16)));
            String gcstr = Marshal.PtrToStringAnsi(OCRpart(@""+"", -1, 0, 0,Convert.ToInt32( "".Split(new char[] {'|' })[0]), Convert.ToInt32("".Split(new char[] { '|' })[1])));
            gcstr = gcstr.Replace('O', '0');
            gcstr = gcstr.Replace('o', '0');
            gcstr = gcstr.Replace('Z', '2');
            gcstr = gcstr.Replace('z', '2');
            gcstr = gcstr.Replace('L', '1');
            gcstr = gcstr.Replace('l', '1');
            gcstr = gcstr.Replace('I', '1');
            gcstr = gcstr.Replace('i', '1');

            gcstr = gcstr.Replace('T', '7');
            gcstr = gcstr.Replace('t', '7');

            gcstr = gcstr.Replace('G', '9');
            gcstr = gcstr.Replace('g', '9');

            gcstr = gcstr.Replace('S', '5');
            gcstr = gcstr.Replace('s', '5');

            gcstr = gcstr.Replace('J', '2');
            gcstr = gcstr.Replace('j', '2');

            gcstr = gcstr.Replace(',', '.');
           

            gcstr = gcstr.Replace("(P1C)","");

            gcstr = gcstr.Replace("-", "");

            gcstr = gcstr.Replace("'", "");
            // gcstr = gcstr.Replace(' ', '');
            // gcstr = gcstr.Trim();
            string result = null;

            for (int i = 0; i < gcstr.Length; i++)
            {
                if (!String.IsNullOrWhiteSpace(gcstr[i].ToString()))
                {
                    result += gcstr[i];
                }
            }
            MessageBox.Show(result);
        }

        private void button1_Click_3(object sender, EventArgs e)
        {
            SystemManage s = new SystemManage();
            s.Show();
        }

        private void LogintreeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //  MessageBox.Show(e.Node.Text+e.Node.Index);
            if (e.Node.Index==4)
            {
                SystemManage s = new SystemManage();
                s.Show();
            }
        }
    }
}
